package project.controller;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import project.model.Response;
import project.model.User;
import project.service.UserService;
import project.utils.JwtUtils;


import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping(value = "/user")
@CrossOrigin
@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JwtUtils jwtUtils;


    @PostMapping
    public int addUser(@ModelAttribute User user) {
        System.out.println("User registered successfully!");
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
       // user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setCreate_time(String.valueOf(LocalDateTime.now()));
        return userService.addUser(user);
    }

//    @PostMapping(value = "/login")
//    public Boolean login(@RequestParam String username, @RequestParam String password, HttpSession session) {
//        password = DigestUtils.md5Hex(password);
//        System.out.println("User logged in successfully!");
//       // password = passwordEncoder.encode(password);
////        session.setAttribute("token",);
//        return userService.login(username, password);
//    }

    @PostMapping(value = "/login")
    public Response<String> login(
            @RequestParam String username,
            @RequestParam String password
    ) {

        // 2. 密码
        password = DigestUtils.md5Hex(password);

        Boolean isLogin = userService.login(username, password);
        System.out.println("User logged in successfully!");
        // 3. 生成 JWT Token
        String token = jwtUtils.generateToken(username);
        //存入redis
        if (isLogin == true){
            User user = userService.selectByName(username);
            Integer uid= user.getUid();

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("password",password);
            userInfo.put("uid",uid);
            userInfo.put("token",token);
//            userInfo.put("avatar","default.jpg");
//            redisTemplate.opsForHash().putAll(username, userInfo);
            String redisKey =  username;
            redisTemplate.opsForHash().putAll(redisKey, userInfo);
            // 设置过期时间
            redisTemplate.expire(redisKey, 60*60*1000, TimeUnit.SECONDS);
        }

        return Response.success(token);
    }
    @GetMapping(value = "/logout")
    public void logout(@RequestParam String loginName){
        System.out.println("user logout,clear redis");
//        redisTemplate.delete("loginName");
//        redisTemplate.delete("password");
        redisTemplate.delete(loginName);
    }

    @GetMapping(value = "/getInfo")
    public User getUser(@RequestParam String loginName) {
        System.out.println("User retrieved successfully!");
        Integer idInt = (Integer) redisTemplate.opsForHash().get(loginName, "uid");

        return userService.selectById(idInt);
    }
    @PutMapping
    public int updateUser(@ModelAttribute User user) {
        System.out.println("User updated successfully!");
      //  user.setPassword(passwordEncoder.encode(user.getPassword()));


        return userService.updateUser(user);
    }
    @DeleteMapping
    public int deleteUser(@RequestParam String uid) {
        System.out.println("User deleted successfully!");
        Integer idInt =uid==null?0:Integer.parseInt(uid);

        return userService.deleteUser(idInt);
    }


}
